package com.example.kfcclient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.Toast;


public class ListFood extends Activity {
	
	private ProgressDialog pDialog;  // khai báo progress Dialog
	
	private static String url_all_product = "http://khoaluankfc.freevnn.com/API/list_product.php"; // khai báo đường dẫn đến server
	
	Editor editor; 
	
	// Json Array
	JSONArray product;
	JSONArray child_product;
	
	//JSon Node Name
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_TITLE = "title";
	private static final String TAG_PRODUCT = "product";
	private static final String TAG_CHILDPRODUCT = "child_product";
	private static final String TAG_NAME = "name";
	private static final String TAG_PRICE = "price";
	private static final String TAG_IMAGE = "image";
	private static final String TAG_ID = "id_title";
	private static final String TAG_CATEID = "id_title";
	private static final String TAG_ITEMID = "id_child";
	
	
	DisplayMetrics metric;
	
	int width;
	int number;
	
	ArrayList<String> nameOrder;
	ArrayList<String> numberOrder;
	ArrayList<Integer> priceOrder;
	ArrayList<String> result_number;
	ArrayList<String> result_name;
	
	public final Context THIS = this;
	
	ListFoodAdapter adapter;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.explist);
		// nhận dữ liệu từ Activity Login gửi qua 
		Bundle extras = getIntent().getExtras();
		if(extras != null)
		{
			number = extras.getInt("table");
			if(number != 0)
			{
				// lưu dữ liệu vào sesssion
				SharedPreferences  pref = getApplicationContext().getSharedPreferences("mypref", MODE_PRIVATE);
				editor = pref.edit();
				editor.putInt("number", number);
				editor.commit();
			}	
		}
		// khởi chạy asynstask
		new LoadProduct().execute();
		
		// xét sự kiện click cho expandlistview
		ExpandableListView list = (ExpandableListView) findViewById(R.id.list);
		list.setOnChildClickListener(new OnChildClickListener() {
			
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		list.setOnGroupClickListener(new OnGroupClickListener() {
			
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		//////////////////////////////////////////////////
			
		metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels;
		// đưa indicator vào thanh group row
		list.setIndicatorBounds(width-GetDipsFromPixel(50), width-GetDipsFromPixel(10));
	}
	
	// xác định vị trí pixel
	public int GetDipsFromPixel(float pixels)
    {
		final float scale = getResources().getDisplayMetrics().density;
		return (int) (pixels * scale + 0.5f);
    }
	
	// bất đồng bô việc load dữ liệu json
	class LoadProduct extends AsyncTask<String, String, String >
	{

		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		InputStream is = null;
		String result = null;
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = new ProgressDialog(ListFood.this);
			pDialog.setMessage("Loading product. please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			try{
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(url_all_product);
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				
				HttpResponse httpResponse = httpClient.execute(httpPost);
				HttpEntity httpEntity = httpResponse.getEntity();
				is = httpEntity.getContent();
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
			}
			catch (Exception e) {
				// TODO: handle exception
				Toast.makeText(ListFood.this, "http connect error : " + e.toString(), Toast.LENGTH_LONG).show();
			}
			return result;
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(String  result) {
			// TODO Auto-generated method stub
			pDialog.dismiss();
			Log.d("product all : ", result);
			ArrayList<Catalogy> groups = new ArrayList<Catalogy>();
			ArrayList<ArrayList<Item>> children = new ArrayList<ArrayList<Item>>();
			ArrayList<Item> itemList ;
			try{
				if(result == null)
					throw new Exception("result is null");
				// phân tích chuổi JSON và đưa vào class item
				JSONObject json_data = new JSONObject(result);
				int success = json_data.getInt(TAG_SUCCESS);
				if(success == 1)
				{
					product = json_data.getJSONArray(TAG_PRODUCT);
					for(int i=0;i<product.length();i++)
					{
						Catalogy catalogy = new Catalogy();
						JSONObject c = product.getJSONObject(i);
						String title = c.getString(TAG_TITLE);
						long id = c.getLong(TAG_ID);
						catalogy.setId(id);
						catalogy.setName(title);
						groups.add(catalogy);
						
						child_product = json_data.getJSONArray(TAG_CHILDPRODUCT);
						itemList = new ArrayList<Item>();
						for(int j=0;j<child_product.length();j++)
						{
							Item item = new Item();
							JSONObject c1 = child_product.getJSONObject(j);
							long cateID = c1.getLong(TAG_CATEID);
							long itemID = c1.getLong(TAG_ITEMID);
							String name = c1.getString(TAG_NAME);
							String image = c1.getString(TAG_IMAGE);
							int price = c1.getInt(TAG_PRICE);
							if(cateID==id)
							{
								item.setCateId(cateID);
								item.setItemId(itemID);
								item.setName(name);
								item.setIcon(image);
								item.setPrice(price);
								item.setNumberFood("1");							
								item.setSelected(false);
								itemList.add(item);
							}
							
						}
						children.add(itemList);
					}
					///////////////////////////////////////
					
					// set adapter cho expandListview
					ExpandableListView list = (ExpandableListView) findViewById(R.id.list);
					adapter = new ListFoodAdapter(THIS,groups,children);
					list.setAdapter(adapter);
					///////////////////////
				}
				else
				{
					Toast.makeText(ListFood.this, "Không có dữ liệu", Toast.LENGTH_LONG).show();
				}
			}
			catch (Exception e) {
				// TODO: handle exception
				Toast.makeText(ListFood.this, "loi gi ko biet" + e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
		
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	// khởi tạo option menu
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflafer = getMenuInflater();
		inflafer.inflate(R.menu.send_menu, menu);
		return true;
	}
	/* (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	// tạo các item menu
	public boolean onOptionsItemSelected(MenuItem itemMenu) {
		// TODO Auto-generated method stub
		switch(itemMenu.getItemId())
		{
			case R.id.send :
				Bundle bundle = new Bundle();
				int numGroup= adapter.getGroupCount();
				nameOrder = new ArrayList<String>();
				numberOrder = new ArrayList<String>();
				priceOrder = new ArrayList<Integer>();
				for(int i=0; i<numGroup;i++)
				{
					int numChild = adapter.getChildrenCount(i);
					for(int j=0;j<numChild;j++)
					{
						if(adapter.isChildSelectable(i, j))
						{
							String name_new = adapter.getChildName(i, j);
							String number_new = adapter.getChildNumber(i, j);
							int price_new = adapter.getChildPrice(i, j);
							// đưa dữ liệu vào arraylist
							priceOrder.add(price_new);
							numberOrder.add(number_new);
							nameOrder.add(name_new);
							//////////////////////////
						}
					}
				}
				
				// đưa dữ liệu arraylist vào bundle
				bundle.putStringArrayList("name", nameOrder);
				bundle.putStringArrayList("number", numberOrder);
				bundle.putIntegerArrayList("price", priceOrder);
				/////////////////////////////////////////////////
				
				// lấy dữ liệu từ session đưa vào bundle
				SharedPreferences  pref = getApplicationContext().getSharedPreferences("mypref", MODE_PRIVATE);
				int sesNumber = pref.getInt("number", -1);
				if(sesNumber != -1)
				{
					bundle.putInt("table", sesNumber);
				}
				/////////////////////////////////////////////
				
				// gọi activity OrderFood
				Intent intent = new Intent(ListFood.this,OrderFood.class);
				intent.putExtras(bundle);
				startActivityForResult(intent,1);
				///////////////////////////////////////////////
				return true;
			default : return super.onOptionsItemSelected(itemMenu);
		}
	}
	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	// nhận giá trị trả về từ Activity OrderFood
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == 1)
		{
			if(resultCode == RESULT_OK)
			{
				// lấy dữ liệu từ intent
				result_number = data.getStringArrayListExtra("result_number");
				result_name = data.getStringArrayListExtra("result_name");
				/////////////////////////////////////////////////////////
				
				int numGroup= adapter.getGroupCount();
				int flag =0;
				for(int i=0; i<numGroup;i++)
				{
					int numChild = adapter.getChildrenCount(i);
					for(int j=0;j<numChild;j++)
					{
						if(adapter.isChildSelectable(i, j))
						{
							
							if(result_number.size() >= flag+1)
							{
								// xóa các checkbox không được sử dụng  khi gọi lại activity
								adapter.SelectItem(i, j,result_name);
								adapter.notifyDataSetChanged();	
								
							}
							// update dữ liệu lên ExpandListview
							adapter.UpdateList(i, j, result_number.get(flag));
							adapter.notifyDataSetChanged();
								
							if(result_number.size() > flag+1)
							{
								flag++;
							}
						}
						
					}
				}
			}
		}
	}
	
}
